<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="题库名称" prop="questionBankName">
            <el-select v-model="form.questionBankName" value-key="questionBankName" placeholder="请输入题库名称" size="small"
                       filterable remote :remote-method="getQuestionBank" @change="function(q) {return bindData(q)}">
              <el-option
                v-for="(q,index) in questionBankListOptions"
                :key="q.questionBankId"
                :label="q.questionBankName"
                :value="q"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目代码" prop="projectCode">
            <el-input v-model="form.projectCode" size="small" width :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" size="small" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="openQuestionBankType">
          <el-form-item label="组别" prop="skillGroup">
            <el-input v-model="form.skillGroup" size="small" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="openQuestionBankType">
          <el-form-item label="等级" prop="skillGrade">
            <el-input v-model="form.skillGrade" size="small" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="类别" v-if="openQuestionBankType" prop="skillPattern">
<!--            <el-input v-model="form.skillPattern" size="small"/>-->
            <el-select v-model="form.skillPattern" placeholder="请选择类别" default-first-option allow-create filterable size="small" style="width: 100%;">
              <el-option v-for="dict in skillPatterns"
                         :key="dict.code" :label="dict.name" :value="dict.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="试题类型" prop="questionType">
            <el-radio-group ref="option" v-model="form.questionType" @change="openQuestionTypeArea">
              <el-radio
                v-for="dict in questionTypeOptions"
                :key="dict.code"
                :label="dict.code"
              >{{ dict.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- 试题类型区域start-->
        <div v-for="q in questionTypeOpen">
          <div v-if="q.open">
            <!-- 题干 -->
            <el-col :span="24">
              <el-form-item label="题干" prop="questionStems">
                <el-input v-model="form.questionStems" placeholder="请输入题干"
                          @click.native="openRichText('questionStems')"/>
              </el-form-item>
            </el-col>
            <!-- 选择类题型区域 -->
            <div v-for="(q,index) in form.questionOptionList" style="width: 100%;display: flex;">
              <el-col :span="1" v-if="openRadio" style="margin: auto">
                <el-radio :key="index" :label="q.selected" @change="bindSingleStandardAnswer(index)"/>
              </el-col>
              <el-col :span="1" v-if="openCheckBox" style="margin: auto">
                <el-checkbox v-model="form.questionOptionList[index].checked" @change="bindMultiStandardAnswer(index)"/>
              </el-col>
              <el-col :span="2" v-if="optionOpen == 'option'" style="margin: auto">
                <el-input v-model="q.optionTag" :disabled="true"/>
              </el-col>
              <el-col :span="19"  v-if="optionOpen == 'option'">
                <el-form-item label="选项内容" style="margin: auto;padding: 10px">
                  <el-input v-model="q.optionContent" placeholder="请输入选项内容"
                            @click.native="openRichText('optionContent',index)"/>
                </el-form-item>
              </el-col>
              <el-col :span="2" style="padding-left: 10px;margin: auto" v-if="openBtn">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeOptionHandle(index)"></el-button>
              </el-col>
            </div>
            <!-- 判断题区域 -->
            <el-col :span="24" v-if="optionOpen == 'estimate'">
              <el-radio-group v-model="form.standardAnswer" style="padding-left: 100px;padding-bottom: 20px">
                <el-radio :label="'0'">正确</el-radio>
                <el-radio :label="'1'">错误</el-radio>
              </el-radio-group>
            </el-col>
          </div>
        </div>
        <el-col :span="24" style="padding-bottom: 10px;padding-left: 600px;" v-if="openBtn">
          <el-button type="primary" size="mini" @click="addOption">添加选项</el-button>
        </el-col>
        <!-- 试题类型区域end-->
        <el-col :span="8" v-if="openStandardAnswer">
          <el-form-item label="标准答案" prop="standardAnswer">
            <el-input v-model="form.standardAnswer" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分值" prop="score">
            <el-input-number v-model="form.score" style="width: 100%" controls-position="right" :min="0" :max="100"
                             placeholder="请输入分值"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="参考解析" prop="questionParse">
            <el-input v-model="form.questionParse" placeholder="请输入参考解析"
                      @click.native="openRichText('questionParse')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="知识类型" prop="knowledgeType" v-if="openType">
<!--            <el-input v-model="form.knowledgeType" placeholder="请输入知识类型"/>-->
            <el-select v-model="form.knowledgeType" placeholder="请选择知识类型" default-first-option allow-create filterable size="small" style="width: 100%;">
              <el-option v-for="dict in knowledgeTypes"
                         :key="dict.code" :label="dict.name" :value="dict.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="专业题型" prop="patternSpecialty" v-if="openType">
            <el-input v-model="form.patternSpecialty" placeholder="请输入专业题型"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否必考" prop="isMustExam">
            <el-radio-group v-model="form.isMustExam">
              <el-radio
                      v-for="dict in isMustExamOptions"
                      :key="dict.code"
                      :label="dict.code"
              >{{ dict.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button size="mini" type="primary" @click="handleReview">预览</el-button>
      <el-button :loading="buttonLoading" size="mini" type="primary" v-if="openSubmit == 'add'" @click="submitForm">保存并继续</el-button>
      <el-button :loading="buttonLoading" size="mini" type="primary" v-if="openSubmit == 'edit'" @click="submitForm">保 存</el-button>
      <el-button :loading="buttonLoading" size="mini" @click="cancel">取 消</el-button>
    </div>
    <!-- 富文本工具 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="800px" append-to-body>
      <rich-text ref="richText" :params="params" @submitContent="submitContent" @cancelRichText="cancelRichText"></rich-text>
    </el-dialog>

    <!-- 预览区域 -->
    <el-dialog :title="'试题预览'" :visible.sync="openReview" v-if="openReview" width="880px" append-to-body>
      <el-row>
        <el-col :span="24" class="text">
          <span v-html="form.questionStems"></span>
        </el-col>
        <div v-if="form.questionOptionList.length">
          <el-col :span="24" v-for="option in form.questionOptionList" class="text">
            {{ option.optionTag + '.' }}{{ option.optionContent }}
          </el-col>
          <el-col :span="24">
            <p>正确答案：{{ form.standardAnswer }}</p>
          </el-col>
        </div>
        <el-col :span="24" v-if="form.questionType == '2'">
          <p>正确答案：{{ estimateAnswer }}</p>
        </el-col>
        <el-col :span="24">
          <p>参考解析</p>
        </el-col>
        <el-col :span="24" class="text">
          <span v-html="form.questionParse"></span>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeReview">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getQuestionBankList, listQuestionBank} from "@/api/question/questionBank"
  import {addQuestion, getQuestionByQuestionId, updateQuestion} from "@/api/question/question";
  import richText from "@/views/question/question/util/ueditor"

  export default {
    name: "radioForm",
    components: {
      richText
    },
    data() {
      return {
        //传给富文本参数
        params: {
          //内容
          content: '',
          //编辑内容类型（题干、选项内容、参考解析）
          type: '',
          //选项下标
          index: undefined
        },
        //富文本标题
        title: '',
        //富文本开关
        open: false,
        //新增或编辑按钮开关,默认新增
        openSubmit: 'add',
        //预览开关
        openReview: false,
        //判断题答案（预览显示用）
        estimateAnswer: '',
        //遮罩层
        buttonLoading: false,
        //题库表
        questionBankListOptions: [],
        //试题类型
        questionTypeOptions: [],
        //是否必考
        isMustExamOptions: [],
        //试题类型开关
        questionTypeOpen: [],
        // 技能鉴定类别
        skillPatterns: [],
        // 工艺知识类型
        knowledgeTypes: [],
        //选项开关
        optionOpen: '',
        //单选框开关
        openRadio: false,
        //复选框开关
        openCheckBox: false,
        //标准答案开关
        openStandardAnswer: false,
        //题库类型开关 技能鉴定
        openQuestionBankType: false,
        // 题库类型开关，工艺
        openType: false,
        //选项添加删除按钮
        openBtn: false,
        form: {
          //默认无图片
          isImage: 'F',
          //是否必考
          isMustExam: 'T',
          //试题类型
          questionType: '0',
          //分值默认5
          score: 5,
          //标准答案
          standardAnswer: '',
          //试题选项
          questionOptionList: []
        },
        rules: {
          questionBankName: {required: true, message: "题库名称不能为空", trigger: "blur"},
          skillPattern: {required: true, message: "类别不能为空", trigger: "blur"},
          knowledgeType: {required: true, message: "知识类型不能为空", trigger: "blur"},
          // questionStems: {required: true, message: "题干不能为空", trigger: "blur"},
          standardAnswer: {required: true, message: "答案不能为空", trigger: "blur"},
          score: {required: true, message: "分值不能为空", trigger: "blur"},
          isMustExam: {required: true, message: "是否必考不能为空", trigger: "blur"}
        }
      }
    },
    created() {
      //试题类型
      this.getDicts("question_type").then(response => {
        this.questionTypeOptions = response.responseBody.result;
      })
      //试题是否必考
      this.getDicts("question_is_must_exam").then(response => {
        this.isMustExamOptions = response.responseBody.result;
      })
      // 技能鉴定类别
      this.getDicts("skill_pattern").then(response => {
        this.skillPatterns = response.responseBody.result;
      })
      // 工艺 知识类型
      this.getDicts("knowledge_type").then(response => {
        this.knowledgeTypes = response.responseBody.result;
      })
      //初始化试题类型开关
      for (let i = 0; i < 7; i++) {
        this.questionTypeOpen.push({open: false});
      }
      //题库信息
      getQuestionBankList({
        'pageParameter': {"page":1,"rows":1000},
        'searchParams': {}
      }).then(response => {
        this.questionBankListOptions = response.responseBody.result;
      })
    },
    methods: {
      init(id) {
        //有id为修改，无id为新增
        if (id) {
          //打开'保存'按钮
          this.openSubmit = 'edit';
          getQuestionByQuestionId(id).then(response => {
            this.openQuestionTypeArea(response.responseBody.questionType, true, response)
            this.form = response.responseBody;
            this.bindData(response.responseBody);
            if (response.responseBody.questionType == 0) {//单选题需要初始化单选框
              for (let i = 0; i < this.form.questionOptionList.length; i++) {
                if (!this.form.questionOptionList[i].isAnswer) {
                  this.bindSingleStandardAnswer(i);
                  break
                }
              }
              //打开单选区域
              this.optionOpen = 'option';
            } else if (response.responseBody.questionType == 1) {//多选题需要初始化复选框
              for (let i = 0; i < this.form.questionOptionList.length; i++) {
                if (!this.form.questionOptionList[i].isAnswer) {
                  this.form.questionOptionList[i].checked = true;
                }
              }
              //打开复选区域
              this.optionOpen = 'option';
            }else if(response.responseBody.questionType == 2){// 初始化判断题
              //打开判断区域
              this.questionOptionList = []; // 清空选项内容
              this.optionOpen = 'estimate';
            }
          });
        } else {
          //默认选中单选
          this.openQuestionTypeArea('0');
          //试题类型默认单选
          this.form.questionType = '0';
          //打开单、多选按钮（添加、删除按钮）
          this.openBtn = true;
        }
      },
      //打开所选试题类型区域并初始化，type取值：0：单选题，1：多选题，2：判断题
      openQuestionTypeArea(type, isEdit) {
        for (let i = 0; i < this.questionTypeOpen.length; i++) {
          this.questionTypeOpen[i].open = false;
        }
        this.questionTypeOpen[type].open = true;
        //初始化单、复选框以及标准答案显示框
        this.initRadioOrCheckBox(type);
        if (isEdit) {
          return
        }
        //单、多选 需要打开按钮(添加删除选项按钮)
        this.openBtn = (type == 0 || type == 1) ? true : false;
        if (type < 2) { //单、多选题
          this.initChoiceQuestion('A', 4);
        }else if(type == 2){//判断题
          this.form.questionOptionList = [];
          this.form.standardAnswer = '0';
          this.optionOpen = 'estimate';
        } else{//其他题型没有选项
          this.form.questionOptionList = [];
          this.optionOpen = '';
        }
      },
      //初始化单、多选框以及标准答案显示框
      initRadioOrCheckBox(type) {
        if (type < 2) {
          //如果type == 1 则打开复选框，否则打开单选框
          this.openCheckBox = type == 1;
          this.openRadio = !this.openCheckBox;
          //初始化标准答案显示框
          this.openStandardAnswer = this.openBtn = true;
          this.form.standardAnswer = '';
        } else {
          this.openRadio = this.openCheckBox = this.openStandardAnswer = this.openBtn = false;
          this.form.standardAnswer = '';
        }
      },
      //初始化选择题, tag: 选项标识，num: 选项数量
      initChoiceQuestion(tag, num) {
        this.form.questionOptionList = [];
        this.optionOpen = 'option';
        let optionTag = tag;
        for (let i = 0; i < num; i++) {
          this.form.questionOptionList.push({
            optionTag: String.fromCharCode(optionTag.charCodeAt(0) + i),
            optionContent: '',
            //选项是否正确：0：正确，1：错误
            isAnswer: 1,
            //单选框状态：选中：1undefined，未选中：''
            selected: '',
            //复选框状态
            checked: false,
            //试题序号
            optionOrder: i
          })
        }
      },
      //绑定单选题正确答案, index:选项下标
      bindSingleStandardAnswer(index) {
        this.form.questionOptionList.forEach(function (item) {
          //所有选项默认错误
          item.isAnswer = 1;
          //清空所有选项
          item.selected = '';
        })
        //选中的选择设为正确
        this.form.questionOptionList[index].isAnswer = 0;
        //设置选项为选中状态
        this.form.questionOptionList[index].selected = undefined;
        //设置回显的正确答案
        this.form.standardAnswer = this.form.questionOptionList[index].optionTag;
      },
      //绑定多选正确答案, index:选项下标
      bindMultiStandardAnswer(index) {
        //根据checked判断复选框的选中状态，如果复选框选中则保存为正确，取消选中则保存为错误。isAnswer取值：0：正确，1：错误
        this.form.questionOptionList[index].isAnswer = this.form.questionOptionList[index].checked ? 0 : 1;
        //存放正确答案
        let standardAnswer = '';
        //根据isAnswer取值拼接正确答案用于回显
        this.form.questionOptionList.forEach(function (item) {
          if (!item.isAnswer) {
            if (standardAnswer === '') {
              standardAnswer = item.optionTag;
            }else {standardAnswer += ','+item.optionTag;}
          }
        })
        //正确答案回显
        this.form.standardAnswer = standardAnswer;
      },
      //增加选项
      addOption() {
        let q = this.form.questionOptionList;
        //获取当前最后一个选项标识
        let optionTag = q[q.length - 1].optionTag;
        //加入新的选项
        q.push({
          optionTag: String.fromCharCode(optionTag.charCodeAt(0) + 1),
          optionContent: '',
          //选项是否正确：0：正确，1：错误
          isAnswer: 1,
          //单选框状态：选中：1undefined，未选中：''
          selected: '',
          //复选框状态
          checked: false,
          //试题序号
          optionOrder: q.length
        })
      },
      //删除选项
      removeOptionHandle(index) {
        //选项总数
        let len = this.form.questionOptionList.length;
        //单、多选最少保留4个选项
        if (len > 4) {
          this.$confirm('确认删除该条选项?', "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() =>{
              this.removeOption(index);
              this.msgSuccess("删除成功");
          }).catch(() => {})
        }else {
          this.msgError("最少需要保留4个选项，删除失败");
        }
      },
      //删除选项
      removeOption(index) {
        let q = this.form.questionOptionList;
        q.splice(index,1);
        //更新选项
        for(let i = index; i < q.length; i++){
          q[i].optionTag = String.fromCharCode(q[i].optionTag.charCodeAt(0) - 1);
          q[i].optionOrder -= 1;
        }
        //获取正确选项
        let isAnswers = [];
        let i;
        for(i in q){
          if(!q[i].isAnswer){
            isAnswers.push(i);
          }
        }
        //重置所有选项单复选框
        q.forEach(item => {
          item.selected = '';
          item.checked = false;
        })
        //更新单复选框
        if(isAnswers.length > 0){
          isAnswers.forEach(i => {
            q[i].selected = undefined;
            q[i].checked = true;
          })
        }
        //存放正确答案
        let standardAnswer = '';
        //根据isAnswer取值拼接正确答案用于回显
        q.forEach(function (item) {
          if (!item.isAnswer) {
            standardAnswer += item.optionTag + ' ';
          }
        })
        //正确答案回显
        this.form.standardAnswer = standardAnswer;
      },

      // 通过名称查询题库
      getQuestionBank(questionBankName) {
        this.queryParams = {
          questionBankName: questionBankName
        }
        getQuestionBankList({
          'searchParams': this.queryParams
        }).then(response => {
          this.questionBankListOptions = response.responseBody.result;
        })
      },

      //绑定相关数据
      bindData(q) {
        this.form.questionBankName = q.questionBankName;
        this.form.questionBankType = q.questionBankType;
        this.form.questionBankId = q.questionBankId;
        this.form.projectCode = q.projectCode;
        this.form.projectName = q.projectName;
        if(q.questionBankType == 1){ // 技能鉴定
          this.form.skillGroup = q.skillGroup;
          this.form.skillGrade = q.skillGrade;
          this.openType = false;
          this.openQuestionBankType = true;
        } else if (q.questionBankType == 2) { // 工艺
          // this.form.knowledgeType = q.knowledgeType;
          this.openType = true;
        } else {
          this.form.knowledgeType = undefined;
          this.form.skillGroup = undefined;
          this.form.skillGrade = undefined;
          this.form.skillPattern = undefined;
          this.openQuestionBankType = false;
          this.openType = false;
        }
      },
      //预览
      handleReview(){
        this.openReview = true;
        // 如果试题存在选项，则去除选项中多余的<p>标签
        if(this.form.questionOptionList.length > 0){
          // 去除选项中多余的<p>标签
          this.form.questionOptionList.forEach(item => {
            item.optionContent = item.optionContent.replace('<p>','').replace('</p>','')
          })
        }
        if(this.form.questionType == '2'){
          this.estimateAnswer = this.form.standardAnswer == '0'? '正确' : '错误';
         }
      },
      //提交
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            //如果有选项则验证试题选项
            if (this.form.questionOptionList.length && this.validateOptionIsNull()) {
              this.msgError("选项内容未全部设置")
              return
            }
            if (this.form.questionStems === undefined || this.form.questionStems.length < 0) {
              this.msgError("题干不能为空");
              return
            }
            //验证是否设置了标准答案
            if (this.validateStandardAnswerIsNotNull()) {
              this.buttonLoading = true;
              if (this.form.questionId != undefined) {
                updateQuestion(this.form).then(response => {
                  if (response.retCode === '200') {
                    this.msgSuccess(response.message);
                    //刷新数据
                    this.$emit("submitForm")
                  }
                  // this.msgSuccess("修改成功");
                  this.$emit("cancelDialog");
                }).finally(() => {
                  this.buttonLoading = false;
                });
              } else {
                addQuestion(this.form).then(response => {
                  if (response.retCode === '200') {
                    this.msgSuccess(response.message);
                  }
                  // this.msgSuccess("新增成功");
                  this.reset();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              }
            }
          }
        });
      },
      //验证所有选项是否都已设置了内容
      validateOptionIsNull() {
        //仅单、多选才有选项
        if (this.form.questionType < 2) {
          let p = this.form.questionOptionList;
          for (let i = 0; i < p.length; i++) {
            if (!p[i].optionContent) {
              return true;
            }
          }
        }
        return false;
      },
      //对于单、多选题需要验证正确答案选项是否已经设置。对于其他题型需要验证是否设置了参考解析
      validateStandardAnswerIsNotNull() {
        let flag = true;
        //0：单选题，1：多选题，2：判断题，3：填空题，4：简答题，5：论述题，6：计算题
        if (this.form.questionType < 3) {
          if (!this.form.standardAnswer) {
            this.msgError("未设置标准答案选项")
            flag = false;
          }
        } else if (!this.form.questionParse) {
          this.msgError("参考解析不能为空")
          flag = false;
        }
        return flag;
      },
      cancel() {
        this.$emit("cancelDialog");
      },
      //重置部分表单项
      reset() {
        if (this.form.questionType < 3) {
          if (this.form.questionType == 1) {//清空多选选项
            this.form.questionOptionList.forEach(item => {
              item.checked = false;
              item.optionContent = '';
            })
          } else {//清空单选及判断选项
            this.form.questionOptionList.forEach(item => {
              item.selected = '';
              item.optionContent = '';
            })
          }
          //清空标准答案
          this.form.standardAnswer = '';
        }
        //清空题干
        this.form.questionStems = '',
          //清空参考解析
          this.form.questionParse = '';
      },
      // 打开富文本
      // type：'questionStems'->题干，'optionContent'->选项内容，'questionParse'->参考解析
      // index：选项下标
      openRichText(type,index){
        this.params.type = type;
        this.params.index = index;
        if(type == 'questionStems'){
          this.params.content = this.form.questionStems;
          this.title = '题干'
        }else if(type == 'optionContent'){
          this.params.content = this.form.questionOptionList[index].optionContent;
          this.title = this.form.questionOptionList[index].optionTag + ' 选项'
        }else if(type == 'questionParse'){
          this.params.content = this.form.questionParse;
          this.title = '参考解析'
        }
        this.open = true;
      },
      //回填富文本内容
      // type：'questionStems'->题干，'optionContent'->选项内容，'questionParse'->参考解析
      // index：选项下标
      submitContent(content,type,optionIndex){
        console.log('content:',content,',type:',type,',optionIndex:',optionIndex)
        if(type == 'questionStems'){
          this.form.questionStems = content;
        }else if(type == 'optionContent'){
          this.form.questionOptionList[optionIndex].optionContent = content;
        }else if(type == 'questionParse'){
          this.form.questionParse = content;
        }
        this.open = false;
      },
      //关闭富文本
      cancelRichText(){
        this.open = false;
      },
      //关闭预览
      closeReview() {
        this.openReview = false;
      }
    }
  }
</script>


<style scoped>
  .title {
    font-size: 24px;
    font-weight: bold;
    padding: 10px;
  }

  .text {
    padding: 10px;
  }
</style>
